package com.sanjiahantang.youjiarole.module.me.order.views.impl;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.module.common.beans.CartGoodsBean;
import com.sanjiahantang.youjiarole.module.evaluate.views.impl.EvaluateGoodsActivity;
import com.sanjiahantang.youjiarole.module.goods.beans.GoodsAttrBean;
import com.sanjiahantang.youjiarole.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiarole.module.invoice.views.InvoiceView;
import com.sanjiahantang.youjiarole.module.me.address.beans.AddressBean;
import com.sanjiahantang.youjiarole.module.me.address.views.AddressView;
import com.sanjiahantang.youjiarole.module.me.order.beans.GHTResultBean;
import com.sanjiahantang.youjiarole.module.me.order.beans.OrderBean;
import com.sanjiahantang.youjiarole.module.me.order.beans.ShopListBean;
import com.sanjiahantang.youjiarole.module.me.order.presenters.OrderPresenter;
import com.sanjiahantang.youjiarole.module.me.order.views.OrderView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by zy on 2017/9/27.
 */
public class OrderActivity extends BaseMvpActivity<OrderView,OrderPresenter> implements View.OnClickListener,
        OrderView {

    private RecyclerView recyclerView;
    private LinearLayout refreshLayout;
    private TextView txtTotal,title;
    private View panelCreate,panelPay,panelEvaluate,llBottom;

    private boolean isRefreshing = false;
    private int type;
    private ShopListBean.Data goodsShopListBean;

    @Override
    public OrderPresenter initPresenter() {
        return new OrderPresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_createorder);
        title = (TextView) findViewById(R.id.title);
        title.setText("确认订单");
        findViewById(R.id.fl_Left).setOnClickListener(this);
        refreshLayout = (LinearLayout) findViewById(R.id.refreshLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        txtTotal = (TextView) findViewById(R.id.txtTotal);
        panelCreate = findViewById(R.id.panelCreate);
        panelPay = findViewById(R.id.panelPay);
        panelEvaluate = findViewById(R.id.panelEvaluate);
        llBottom = findViewById(R.id.llBottom);


        findViewById(R.id.txtSubmit).setOnClickListener(this);
        findViewById(R.id.btnEvaluate).setOnClickListener(this);

        presenter.initRecyclerView($this,recyclerView,ACTIVITY_ORDER_CREATE);
        type = getIntent().getIntExtra(KEY_TYPE,0);
        switch (type){
            case ORDER_TYPE_GOODS:
                panelCreate.setVisibility(View.VISIBLE);
                initGoodsCreate();
                break;
            case ORDER_TYPE_CART:
                panelCreate.setVisibility(View.VISIBLE);
                initCartCreate();
                break;
            case ORDER_TYPE_CANCEL:
                panelPay.setVisibility(View.VISIBLE);
                initGoodsOrder();
                break;
            case ORDER_TYPE_PAY:
                panelPay.setVisibility(View.VISIBLE);
                initGoodsOrder();
                break;
            case ORDER_TYPE_CLOSE:
                initGoodsOrder();
                break;
            case ORDER_TYPE_PAYED:
                initGoodsOrder();
                break;
            case ORDER_TYPE_COMPLETE:
                panelEvaluate.setVisibility(View.VISIBLE);
                initGoodsOrder();
                break;
            case ORDER_TYPE_EVALUATED:
                initGoodsOrder();
                break;
            case ORDER_TYPE_PART_PAY:
                panelCreate.setVisibility(View.VISIBLE);
                initGoodsOrder();
                break;
            default:
                initGoodsOrder();
                break;
        }


    }


    //我的订单
    private void initGoodsOrder() {
        Bundle b = getIntent().getBundleExtra(KEY_PARAM);
        ShopListBean.Data goods = (ShopListBean.Data) b.getSerializable("goods");
        presenter.searchGoodsRaForCode($this,goods.getOrderCode(), new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] para = (Object[]) content;
                switch ((int)para[0]){
                    case CALLBACK_TYPE_ORDER_DATA:
                        fillRecycler((ShopListBean.Data)para[1]);
                        break;
                    case CALLBACK_TYPE_FAILURE:
                        Utils.showToast($this,"获取订单失败");
                        finish();
                        break;
                }
            }
        });
    }

    private void fillRecycler(ShopListBean.Data goods){
        if (goods == null){
            Utils.showToast($this,"订单找不到了");
            finish();
            return;
        }
        title.setText("订单详情");
        goodsShopListBean = goods;
        OrderBean.Data data = new OrderBean.Data();
        ArrayList<CartGoodsBean.Data> list = new ArrayList<>();
        for (int i = 0,max = goods.getGoodsInfoDtoList().size();i<max;i++){
            ShopListBean.Data.GoodsInfoDtoListBean item = goods.getGoodsInfoDtoList().get(i);
            CartGoodsBean.Data cart = new CartGoodsBean.Data();
            cart.setSupplyName(null);
            cart.setSupplyId(null);
            cart.setUrl(item.getUrl());
            cart.setNumber(item.getCount());
            cart.setMgiId(item.getMgiId());
            cart.setSkuId(String.valueOf(item.getSkuFaId()));
            cart.setBasePrice(String.format("%.2f",(float)item.getPrice()));
            cart.setGoodsName(item.getRecordName());
            cart.setMgpiValue(item.getMgpiValue());

            list.add(cart);
        }
        data.setGoods(list);
        data.setConsumerMessage(goods.getBuyPersonMessage());
        data.setInvoice(goods.getOrderInvoiceInfoDto());
        if(OrderView.TYPE_PART_PAY == goods.getStatusId()){
            data.setRemain(String.format(FORMAT_ORDER_REMAIN,
                    goods.getAreadyResult(),
                    (goods.getPayMoney() - goods.getAreadyResult())));
        }
        ArrayList<Integer> typeList = new ArrayList<>();
        typeList.add(ORDER_PAGE_HOLDER_TYPE_STATE);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_ADDRESS);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_GOODS_LIST);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_GHT);
        //根据2017年12月26日需求更改 订单完成之前不显示发票
        if (goods.getStatusId() == OrderView.TYPE_EVALUATED || goods.getStatusId() == OrderView.TYPE_COMPLETE){
            typeList.add(ORDER_PAGE_HOLDER_TYPE_INVOICE);
        }
        typeList.add(ORDER_PAGE_HOLDER_TYPE_CONSUMER_MESSAGE);
        data.setJdOrderInfo(goods.getJdOrderInfo());
        data.setmOrderInfo(goods.getmOrderInfo());
        presenter.setData(data,typeList,goods);
        switch (goods.getStatusId()){
            case OrderView.TYPE_UN_PAY:
                TextView btnPay = (TextView) findViewById(R.id.btnPayForStateUnPay);
                btnPay.setText(String.format("本次应付%.2f元",(float)goods.getPayResult()));
                btnPay.setOnClickListener(this);
                findViewById(R.id.btnCancel).setOnClickListener(this);
                panelPay.setVisibility(View.VISIBLE);
                panelEvaluate.setVisibility(View.GONE);
                panelCreate.setVisibility(View.GONE);
                break;
            case OrderView.TYPE_PART_PAY:
                TextView btnSubmit = (TextView) findViewById(R.id.txtSubmit);
                btnSubmit.setText("去付款");
                TextView txtTotal = (TextView) findViewById(R.id.txtTotal);
                txtTotal.setText(String.format("%.2f",(float)goods.getPayResult()));
                btnSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (goodsShopListBean != null){
                            goodsShopListBean.setToken(ConfigValue.DATA_KEY);
                            goodsShopListBean.setPhoneTypeId(0);
                            presenter.doPay($this,goodsShopListBean);
                        }
                    }
                });
                panelPay.setVisibility(View.GONE);
                panelEvaluate.setVisibility(View.GONE);
                panelCreate.setVisibility(View.VISIBLE);
                break;
            case OrderView.TYPE_CLOSE:case OrderView.TYPE_EVALUATED:
                llBottom.setVisibility(View.GONE);
                break;
            case OrderView.TYPE_COMPLETE:
                panelEvaluate.setVisibility(View.VISIBLE);
                panelCreate.setVisibility(View.GONE);
                panelPay.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                break;
            default:
                llBottom.setVisibility(View.GONE);
                break;
        }


        presenter.loadOrder($this,goods.getUserAddressId() == 0 ? null : String.valueOf(goods.getUserAddressId()));
    }

    //购物车
    private void initCartCreate() {
        Bundle b = getIntent().getBundleExtra(KEY_PARAM);
        ArrayList<CartGoodsBean.Data> list = (ArrayList<CartGoodsBean.Data>) b.getSerializable("cart");
        int num = 0;
        double price = 0;
        for (int i = 0,max = list.size();i<max;i++){
            num = list.get(i).getNumber();
            price += Double.parseDouble(list.get(i).getBasePrice()) * num;
        }
        OrderBean.Data data = new OrderBean.Data();
        data.setGoods(list);
        data.setIsShoppingCartOrder(1);
        ArrayList<Integer> typeList = new ArrayList<>();
        typeList.add(ORDER_PAGE_HOLDER_TYPE_ADDRESS);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_GOODS_LIST);
        //根据2017年12月26日需求更改 订单完成之前不显示发票
        //typeList.add(ORDER_PAGE_HOLDER_TYPE_INVOICE);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_CONSUMER_MESSAGE);
        presenter.setData(data,typeList,null);
        txtTotal.setText(String.format("%.2f",price));
        presenter.loadOrder($this,null);
    }

    //商品直接付款
    private void initGoodsCreate() {
        Bundle b = getIntent().getBundleExtra(KEY_PARAM);
        GoodsBean.Data goodsBean = (GoodsBean.Data) b.getSerializable("goods");
        GoodsAttrBean.SkuData sku = (GoodsAttrBean.SkuData) b.getSerializable("sku");
        int num = b.getInt("num");
        CartGoodsBean.Data beanData = new CartGoodsBean.Data();
        beanData.setBasePrice(sku.getResultPrice());
        beanData.setUrl(goodsBean.getUrl());
        beanData.setGoodsName(goodsBean.getGoodsName());
        beanData.setMgiId(goodsBean.getMgiId());
        beanData.setMgpiValue(sku.getMgpiValue());
        beanData.setMgsciId(goodsBean.getMgcId());
        beanData.setNumber(num);
        beanData.setSkuId(sku.getSkuId());
        beanData.setStockCount(sku.getStockCount());
        beanData.setSupplyId(goodsBean.getSupplyId());
        beanData.setSupplyName(goodsBean.getSupplyName());
        OrderBean.Data data = new OrderBean.Data();
        List<CartGoodsBean.Data> arr = new ArrayList<>();
        arr.add(beanData);
        data.setGoods(arr);
        ArrayList<Integer> typeList = new ArrayList<>();
        typeList.add(ORDER_PAGE_HOLDER_TYPE_ADDRESS);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_GOODS_LIST);
        //根据2017年12月26日需求更改 订单完成之前不显示发票
        //typeList.add(ORDER_PAGE_HOLDER_TYPE_INVOICE);
        typeList.add(ORDER_PAGE_HOLDER_TYPE_CONSUMER_MESSAGE);
        presenter.setData(data,typeList,null);
        data.setIsShoppingCartOrder(0);
        txtTotal.setText(String.valueOf(num * (Double.valueOf(sku.getResultPrice()))));
        presenter.loadOrder($this,null);
    }

    @Override
    public void initData() {
        presenter.setOnLoadListener(new OnLoadListener(){

            @Override
            public void setGoodsNumber(int count, float price) {
                txtTotal.setText(String.valueOf(price));
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == INTENT_INVOICE && resultCode == RESULT_OK){
            initGoodsOrder();
        }
        if (requestCode == INTENT_ADDRESS && resultCode == RESULT_OK){
            if(data != null){
                AddressBean.Data address = new AddressBean.Data();
                address.setCustomerName(data.getStringExtra(AddressView.KEY_NAME));
                address.setFullAddress(data.getStringExtra(AddressView.KEY_ADDRESS));
                address.setCellPhone(data.getStringExtra(AddressView.KEY_PHONE));
                address.setUcaId(data.getIntExtra(AddressView.KEY_ID,0));
                presenter.setAddress(address);
            }
        }

        if (requestCode == INTENT_EVALUATE && resultCode == RESULT_OK){
            initGoodsOrder();
        }

        if (requestCode == 1000 && data != null){
            String resultData = data.getExtras().getString("result_data");
            Log.e("result_data",resultData);
            GHTResultBean resultBean = new Gson().fromJson(resultData,GHTResultBean.class);
            presenter.goodsBalancePay($this,resultBean.getPay_data(),new BaseView.OnLoadListener(){

                @Override
                public void onLoad(Object content) {
                    initGoodsOrder();
                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_Left:
                finish();
                break;
            case R.id.txtSubmit://提交
                switch (type){
                    case ORDER_TYPE_GOODS:case ORDER_TYPE_CART:
                        presenter.doSubmitOrder($this,recyclerView);
                        break;
                }
                break;
            case R.id.btnPayForStateUnPay:
                if (goodsShopListBean != null){
                    goodsShopListBean.setToken(ConfigValue.DATA_KEY);
                    goodsShopListBean.setPhoneTypeId(1);
                    presenter.doPay($this,goodsShopListBean);
                }

                break;
            case R.id.btnCancel:
                ShopListBean.Data goods2 = (ShopListBean.Data) getIntent().getBundleExtra(KEY_PARAM).getSerializable("goods");
                goods2.setToken(ConfigValue.DATA_KEY);
                goods2.setPhoneTypeId(1);
                presenter.doCancel($this,goods2);
                break;
            case R.id.btnEvaluate:
                Intent intent = new Intent($this, EvaluateGoodsActivity.class);
                intent.putExtra(KEY_PARAM,getIntent().getBundleExtra(KEY_PARAM));
                startActivityForResult(intent,INTENT_EVALUATE);
                break;
        }
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public void hideProgress() {
        super.hideProgress();
    }



}
